﻿using CMS.Tool.WebApi.Models.Base;
using CodeCarvings.Piczard;
using CodeCarvings.Piczard.Filters.Watermarks;
using ImageProcessor;
using ImageProcessor.Imaging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using IO = System.IO;

namespace CodeTool.WebApi.Models.Uploader
{
    public class ImageUploder
    {
        public PostResult<string> ImageResize(int width, int height, HttpFileCollection httpFiles)
        {
            var folder = "D:\\upload";
            var file = httpFiles[0];
            var contentSize = file.ContentLength;//文件大小字节b
            var contenType = file.ContentType;//格式
            if (!IO.Directory.Exists(folder)) IO.Directory.CreateDirectory(folder);
            var filename = file.FileName;
            var extension = filename.Substring(filename.LastIndexOf(".")).ToLower(); // 扩展名
            var key = filename.Replace(extension, "_") + DateTime.Now.ToString("yyyyMMddHHmmssfff") + extension;
            var path = $"{folder}//{key}";
            file.SaveAs(path);

            var bytes = File.ReadAllBytes(path);
            var outpath = $"{folder}//{key.Replace(".", $"_{width}X{height}.")}";
            
            #region 缩略图
            using (Stream inStream = new MemoryStream(bytes))
            {
                ImageProcessingJob jobThumb = new ImageProcessingJob();
                jobThumb.Filters.Add(new FixedResizeConstraint(width, height));
                jobThumb.SaveProcessedImageToFileSystem(inStream, outpath);
                inStream.Position = 0;//指针复位
            }
            #endregion

            #region 水印
            var waterpath = "E:\\watermark.jpg";
            var readbytes = File.ReadAllBytes(outpath);
            ImageWatermark imgWatermark = new ImageWatermark(waterpath);//水印图片位置
            imgWatermark.ContentAlignment = ContentAlignment.MiddleCenter;//水印位置
            imgWatermark.Alpha = 100;//透明度，需要水印图片是背景透明的png图片
            ImageProcessingJob jobNormal = new ImageProcessingJob();
            jobNormal.Filters.Add(imgWatermark);//添加水印
            //jobNormal.Filters.Add(new FixedResizeConstraint(600, 600));//添加图片缩放，水印可能会不清晰
            jobNormal.SaveProcessedImageToFileSystem(readbytes, outpath); 
            #endregion

            return new PostResult<string> { data = "", msg = "ok" };
        }

    }
}